//
//  MessageController.swift
//  mggz
//
//  Created by 匀视网Mac on 2018/5/23.
//  Copyright © 2018年 爱丽丝的梦境. All rights reserved.
//

import UIKit
import RxCocoa
import RxSwift
import MJRefresh

class MessageController: UIViewController {
    var page = 1
    
    var emptyview:EmptyView?
    
    var datavariable:PublishSubject<[MessageItem]> = PublishSubject()
    var datalist = [MessageItem]()
    var isPresent:Bool? = false
    
    lazy var titleLayout:PresentTitleView = {
        var view = PresentTitleView(frame: CGRect.zero,_title: "待办消息",_close:self.clickNormal!)
        return view
    }()
    
    var clickNormal:NormalClick?
    
    var tableView:UITableView = {
        var view = UITableView()
        view.separatorStyle = .singleLine
        view.tableFooterView = UIView(frame: CGRect.zero)
        view.register(UINib(nibName: "MsgCell", bundle: nil), forCellReuseIdentifier: "cell")
        return view
    }()
    func closeViewController(){
        self.dismiss(animated: true, completion: nil)
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.navigationItem.title = "待办消息"
        QWTextWithStatusHud("正在加载...", target: self.view)
        
        self.clickNormal = {
            self.closeViewController()
        }
        
        let tableHeader = MJRefreshNormalHeader(refreshingTarget: self, refreshingAction: #selector(refresh))
        tableHeader?.stateLabel.isHidden = true
        self.tableView.mj_header = tableHeader
        
        let tableNormalFoot = MJRefreshBackNormalFooter(refreshingTarget: self, refreshingAction: #selector(loadMore))
        tableNormalFoot?.stateLabel.isHighlighted = true
        self.tableView.mj_footer = tableNormalFoot
        self.tableView.estimatedRowHeight = 90
        self.tableView.rowHeight = UITableViewAutomaticDimension
        
        self.datavariable.asObservable().bind(to: self.tableView.rx.items){
            (_,index,element) in
            
            var cell = self.tableView.dequeueReusableCell(withIdentifier: "cell", for: IndexPath(row: index, section: 0)) as? MsgCell
            
            if cell == nil {
                cell = MsgCell(style: UITableViewCellStyle.default, reuseIdentifier: "cell")
            }
            cell?.itemdata = self.datalist[index]
            
            
            return cell!
        }
        
        self.tableView.rx.itemSelected.subscribe({
            index in
            self.tableView.deselectRow(at: index.element!, animated: true)
            
            if self.datalist[(index.element?.row)!].IsDetail ?? false {
                do{
                    var vc = MessageHandlerController(nibName: "MessageHandlerController", bundle: nil)
                    
                    let itemdata = self.datalist[(index.element?.row)!]
                    let jsonstr = (itemdata.JsonParams ?? "").replacingOccurrences(of: "/", with: "", options: String.CompareOptions.literal, range: nil)
                    var data = jsonstr.data(using: String.Encoding.utf8)
                    let dic = try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.mutableContainers) as? Dictionary<String,Any>
                    vc.itemModel = itemdata
                    vc.jsonParams = dic
                    
                    vc.modalPresentationStyle = .overCurrentContext
                    self.present(vc, animated: true, completion: nil)
                }catch(let error){
                    
                }
                
            }
            
        })
        if self.isPresent ?? false{
            self.view.addSubview(self.titleLayout)
        }
        
        self.view.addSubview(self.tableView)
        
        self.getData()

        
    }
    
    override func viewDidLayoutSubviews() {
        if isPresent ?? false{
            self.titleLayout.snp.updateConstraints({ (make) in
                make.top.equalTo(self.view.snp.top)
                make.left.equalTo(self.view.snp.left)
                make.right.equalTo(self.view.snp.right)
                make.height.equalTo(64)
            })
            
            self.tableView.snp.updateConstraints { (make) in
                make.top.equalTo(self.titleLayout.snp.bottom)
                make.bottom.equalTo(self.view.snp.bottom)
                make.left.equalTo(self.view.snp.left)
                make.right.equalTo(self.view.snp.right)
            }
            
        }else{
            self.tableView.snp.updateConstraints { (make) in
                make.top.equalTo(self.view.snp.top)
                make.bottom.equalTo(self.view.snp.bottom)
                make.left.equalTo(self.view.snp.left)
                make.right.equalTo(self.view.snp.right)
            }
        }
        
    }
    
    @objc func refresh(){
        self.page = 1
        self.getData()
    }
    @objc func loadMore(){
        self.page += 1
        self.getData()
    }
    
    func getData(){
        var params:[String:Any] = ["pageIndex":String(page),"pageSize":String(PageSize)]
        MNetHttp.sharedInstance.postSingle(API_CALL_METHOD, method: .MESSAGE, params: &params, type: MessageList.self, success: { (bean,_) in
            QWHudDiss(self.view)
            guard let data = bean as? MessageList else{
                return
            }
            if self.page == 1{
                self.datalist.removeAll()
            }
            if self.page == 1 && (data.Result?.Items == nil || data.Result?.Items?.count == 0){
                self.addEmptyView("暂无数据")
            }else if self.page > 1 && (data.Result?.Items == nil || data.Result?.Items?.count ?? 0 < PageSize){
                self.tableView.mj_footer.endRefreshingWithNoMoreData()
                
            }else{
                self.tableView.mj_footer.endRefreshing()
                self.tableView.mj_header.endRefreshing()
            }
            self.datalist.append(contentsOf: data.Result?.Items ?? [MessageItem]())
            self.datavariable.onNext(self.datalist)
        }) { (error) in
            QWHudDiss(self.view)
            self.addEmptyView("数据异常")
        }
    }
    
    
    func addEmptyView(_ titleStr:String){
        guard let view = emptyview else {
            self.emptyview = EmptyView(frame: CGRect.zero, _title: titleStr, _top: Float(SCREEN_HEIGHT/5))
            self.view.addSubview(self.emptyview!)
            self.emptyview!.snp.updateConstraints({ (maker) in
                maker.top.equalTo(self.view.snp.top)
                maker.left.equalTo(self.view.snp.left)
                maker.right.equalTo(self.view.snp.right)
                maker.bottom.equalTo(self.view.snp.bottom)
            })
            return
        }
    }
    
    func removeEmpty(){
        self.emptyview?.removeFromSuperview()
        self.emptyview = nil
    }
    
    

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}
